{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .account-detail-container {
        max-width: 1200px;
        margin: 0 auto;
    }

    .user-profile-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
    }

    .user-avatar {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2rem;
        margin-bottom: 1rem;
    }

    .balance-overview {
        background: rgba(255,255,255,0.1);
        border-radius: 10px;
        padding: 1.5rem;
        margin-top: 1.5rem;
    }

    .balance-item {
        text-align: center;
        padding: 0.5rem;
    }

    .balance-value {
        font-size: 1.5rem;
        font-weight: bold;
        display: block;
    }

    .balance-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }

    .detail-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-item {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 1.5rem;
        text-align: center;
        transition: transform 0.3s ease;
    }

    .stat-item:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem;
        font-size: 1.5rem;
    }

    .stat-icon.success {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }

    .stat-icon.danger {
        background: linear-gradient(135deg, #dc3545, #e83e8c);
        color: white;
    }

    .stat-icon.warning {
        background: linear-gradient(135deg, #ffc107, #fd7e14);
        color: white;
    }

    .stat-icon.info {
        background: linear-gradient(135deg, #17a2b8, #6f42c1);
        color: white;
    }

    .stat-value {
        font-size: 1.5rem;
        font-weight: bold;
        color: #495057;
        margin-bottom: 0.5rem;
    }

    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .transaction-list {
        max-height: 400px;
        overflow-y: auto;
    }

    .transaction-item {
        border-left: 4px solid #dee2e6;
        padding: 1rem;
        margin-bottom: 1rem;
        background: #f8f9fa;
        border-radius: 0 8px 8px 0;
        transition: all 0.3s ease;
    }

    .transaction-item:hover {
        background: #e9ecef;
        transform: translateX(5px);
    }

    .transaction-item.income {
        border-left-color: #28a745;
    }

    .transaction-item.expense {
        border-left-color: #dc3545;
    }

    .transaction-amount {
        font-weight: bold;
        font-size: 1.1rem;
    }

    .amount-positive {
        color: #28a745;
    }

    .amount-negative {
        color: #dc3545;
    }

    .reservation-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
        transition: all 0.3s ease;
    }

    .reservation-card:hover {
        border-color: #007bff;
        box-shadow: 0 2px 8px rgba(0,123,255,0.2);
    }


    .quick-actions {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }

    .quick-action-btn {
        padding: 1rem;
        border-radius: 10px;
        text-decoration: none;
        color: white;
        text-align: center;
        transition: all 0.3s ease;
        font-weight: 500;
    }

    .quick-action-btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        color: white;
    }

    .quick-action-btn.success {
        background: linear-gradient(135deg, #28a745, #20c997);
    }

    .quick-action-btn.warning {
        background: linear-gradient(135deg, #ffc107, #fd7e14);
    }

    .quick-action-btn.info {
        background: linear-gradient(135deg, #17a2b8, #6f42c1);
    }

    .quick-action-btn.primary {
        background: linear-gradient(135deg, #007bff, #6610f2);
    }

    .chart-container {
        background: white;
        border-radius: 10px;
        padding: 1.5rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
    }

    .alert-custom {
        border: none;
        border-radius: 10px;
        padding: 1rem 1.5rem;
    }

    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: 1fr 1fr;
        }

        .quick-actions {
            grid-template-columns: 1fr;
        }

        .balance-overview .row > div {
            margin-bottom: 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="account-detail-container">
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col-12">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ url_for('dashboard.index') }}">管理首页</a></li>
                        <li class="breadcrumb-item"><a href="{{ url_for('admin_accounts.list_accounts') }}">用户账户管理</a></li>
                        <li class="breadcrumb-item active">{{ user.real_name or user.username }}</li>
                    </ol>
                </nav>
            </div>
        </div>

        <!-- 用户资料卡片 -->
        <div class="user-profile-card">
            <div class="row align-items-center">
                <div class="col-md-3 text-center">
                    <div class="user-avatar">
                        <i class="fas fa-user"></i>
                    </div>
                    <h4 class="mb-1">{{ user.real_name or user.username }}</h4>
                    <p class="mb-0 opacity-75">{{ user.username }}</p>
                </div>

                <div class="col-md-4">
                    <div class="row">
                        <div class="col-6">
                            <strong>手机号码</strong>
                            <div>{{ user.phone or '未设置' }}</div>
                        </div>
                        <div class="col-6">
                            <strong>用户角色</strong>
                            <div>
                                {% if user.role == 'student' %}学员
                                {% elif user.role == 'coach' %}教练
                                {% elif user.role == 'admin' %}管理员
                                {% else %}{{ user.role }}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-6">
                            <strong>注册时间</strong>
                            <div>{{ user.created_at.strftime('%Y-%m-%d') }}</div>
                        </div>
                        <div class="col-6">
                            <strong>账户状态</strong>
                            <div>{{ user.status if user.status else '未知状态' }}</div>
                        </div>
                    </div>
                </div>

                <div class="col-md-5">
                    <div class="balance-overview">
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="balance-item">
                                    <span class="balance-value">¥{{ "%.2f"|format(account_summary.balance) }}</span>
                                    <small class="balance-label">账户余额</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="balance-item">
                                    <span class="balance-value">¥{{ "%.2f"|format(account_summary.available_balance) }}</span>
                                    <small class="balance-label">可用余额</small>
                                </div>
                            </div>
                        </div>

                        <div class="mt-3">
                            <small class="opacity-75">
                                账户状态：
                                <span class="badge bg-success">正常</span>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 快捷操作 -->
        <div class="quick-actions">
            <a href="{{ url_for('admin_accounts.offline_recharge', user_id=user.id) }}"
               class="quick-action-btn success">
                <i class="fas fa-plus-circle d-block mb-2"></i>
                线下充值
            </a>
            <a href="{{ url_for('accounts.transactions', user_id=user.id) }}"
               class="quick-action-btn info">
                <i class="fas fa-list d-block mb-2"></i>
                交易记录
            </a>
            <a href="{{ url_for('student_reservations.index', user_id=user.id) }}"
               class="quick-action-btn primary">
                <i class="fas fa-calendar d-block mb-2"></i>
                预约记录
            </a>
        </div>

        <!-- 统计数据 -->
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-icon success">
                    <i class="fas fa-arrow-up"></i>
                </div>
                <div class="stat-value">¥{{ "%.2f"|format(monthly_stats.total_income) }}</div>
                <div class="stat-label">本月收入</div>
            </div>

            <div class="stat-item">
                <div class="stat-icon danger">
                    <i class="fas fa-arrow-down"></i>
                </div>
                <div class="stat-value">¥{{ "%.2f"|format(monthly_stats.total_expense) }}</div>
                <div class="stat-label">本月支出</div>
            </div>

            <div class="stat-item">
                <div class="stat-icon warning">
                    <i class="fas fa-exchange-alt"></i>
                </div>
                <div class="stat-value">{{ monthly_stats.total_transactions }}</div>
                <div class="stat-label">本月交易数</div>
            </div>

            <div class="stat-item">
                <div class="stat-icon info">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-value">¥{{ "%.2f"|format(monthly_stats.average_per_transaction) }}</div>
                <div class="stat-label">平均单笔</div>
            </div>

            <div class="stat-item">
                <div class="stat-icon success">
                    <i class="fas fa-calendar-check"></i>
                </div>
                <div class="stat-value">{{ recent_reservations|length }}</div>
                <div class="stat-label">最近预约</div>
            </div>

            <div class="stat-item">
                <div class="stat-icon info">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-value">
                    -
                </div>
                <div class="stat-label">最后交易</div>
            </div>
        </div>

        <div class="row">
            <!-- 最近交易记录 -->
            <div class="col-lg-6">
                <div class="detail-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="fas fa-history me-2"></i>最近交易记录
                        </h5>
                        <a href="{{ url_for('accounts.transactions', user_id=user.id) }}"
                           class="btn btn-sm btn-outline-primary">
                            查看全部
                        </a>
                    </div>

                    <div class="transaction-list">
                        {% if recent_transactions %}
                            {% for transaction in recent_transactions %}
                            <div class="transaction-item {{ 'income' if transaction.amount > 0 else 'expense' }}">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="fw-medium">{{ transaction.description }}</div>
                                        <small class="text-muted">
                                            <i class="fas fa-clock me-1"></i>
                                            {{ transaction.created_at.strftime('%m-%d %H:%M') }}
                                            {% if transaction.payment_method %}
                                                | {{ transaction.payment_method }}
                                            {% endif %}
                                        </small>
                                    </div>
                                    <div class="transaction-amount {{ 'amount-positive' if transaction.amount > 0 else 'amount-negative' }}">
                                        {{ '+' if transaction.amount > 0 else '' }}¥{{ "%.2f"|format(transaction.amount) }}
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-receipt fa-2x mb-3"></i>
                                <p>暂无交易记录</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 最近预约记录 -->
            <div class="col-lg-6">
                <div class="detail-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="fas fa-calendar-alt me-2"></i>最近预约记录
                        </h5>
                        <a href="{{ url_for('student_reservations.index', user_id=user.id) }}"
                           class="btn btn-sm btn-outline-primary">
                            查看全部
                        </a>
                    </div>

                    <div>
                        {% if recent_reservations %}
                            {% for reservation in recent_reservations %}
                            <div class="reservation-card">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="fw-medium">
                                            {{ reservation.reservation_date.strftime('%m月%d日') }}
                                            {{ reservation.start_time.strftime('%H:%M') }}-{{ reservation.end_time.strftime('%H:%M') }}
                                        </div>
                                        <small class="text-muted">
                                            {% if reservation.coach %}
                                                教练：{{ reservation.coach.real_name or reservation.coach.username }}
                                            {% endif %}
                                            {% if reservation.table %}
                                                | 球台：{{ reservation.table.name }}
                                            {% endif %}
                                        </small>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold">¥{{ "%.2f"|format(reservation.price) }}</div>
                                        <small>
                                            {% if reservation.status == 'confirmed' %}
                                                <span class="text-success">已确认</span>
                                            {% elif reservation.status == 'pending' %}
                                                <span class="text-warning">待确认</span>
                                            {% elif reservation.status == 'cancelled' %}
                                                <span class="text-danger">已取消</span>
                                            {% elif reservation.status == 'completed' %}
                                                <span class="text-info">已完成</span>
                                            {% else %}
                                                <span class="text-muted">{{ reservation.status }}</span>
                                            {% endif %}
                                        </small>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-calendar fa-2x mb-3"></i>
                                <p>暂无预约记录</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 年度统计图表 -->
        {% if yearly_stats and not yearly_stats.get('error') %}
        <div class="row">
            <div class="col-12">
                <div class="chart-container">
                    <h5 class="mb-4">
                        <i class="fas fa-chart-bar me-2"></i>年度消费趋势
                    </h5>

                    <div class="row text-center mb-4">
                        <div class="col-md-3">
                            <div class="h4 text-success">¥{{ "%.2f"|format(yearly_stats.total_income) }}</div>
                            <small class="text-muted">年度收入</small>
                        </div>
                        <div class="col-md-3">
                            <div class="h4 text-danger">¥{{ "%.2f"|format(yearly_stats.total_expense) }}</div>
                            <small class="text-muted">年度支出</small>
                        </div>
                        <div class="col-md-3">
                            <div class="h4 text-primary">{{ yearly_stats.total_transactions }}</div>
                            <small class="text-muted">交易笔数</small>
                        </div>
                        <div class="col-md-3">
                            <div class="h4 text-info">¥{{ "%.2f"|format(yearly_stats.average_per_transaction) }}</div>
                            <small class="text-muted">平均金额</small>
                        </div>
                    </div>

                    {% if yearly_stats.by_date %}
                    <div class="row">
                        <div class="col-12">
                            <canvas id="yearlyChart" height="300"></canvas>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        {% endif %}


    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    // 初始化年度趋势图表
    {% if yearly_stats and yearly_stats.by_date %}
    initYearlyChart();
    {% endif %}

    // 页面加载动画
    $('.detail-card').each(function(index) {
        $(this).delay(index * 200).fadeIn(600);
    });
});

// 年度趋势图表
function initYearlyChart() {
    const ctx = document.getElementById('yearlyChart');
    if (!ctx) return;

    const dateData = {{ yearly_stats.by_date | tojson }};
    const dates = Object.keys(dateData).sort();
    const amounts = dates.map(date => parseFloat(dateData[date]));

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates.map(date => {
                const d = new Date(date);
                return (d.getMonth() + 1) + '/' + d.getDate();
            }),
            datasets: [{
                label: '日消费金额',
                data: amounts,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '年度消费趋势分析'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toFixed(2);
                        }
                    }
                }
            }
        }
    });
}


// 显示提示信息
function showAlert(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    // 3秒后自动隐藏
    setTimeout(() => {
        $('.alert').fadeOut();
    }, 3000);
}

// 实时更新余额显示
function updateBalanceDisplay() {
    $.get('{{ url_for("admin_accounts.api_get_user_balance", user_id=user.id) }}')
        .done(function(response) {
            if (response.success) {
                // 更新余额显示，添加动画效果
                $('.balance-value').each(function(index) {
                    const newValue = [
                        response.data.balance.toFixed(2),
                        response.data.available_balance.toFixed(2)
                    ][index];

                    if (newValue) {
                        $(this).fadeOut(200, function() {
                            $(this).text('¥' + newValue).fadeIn(200);
                        });
                    }
                });
            }
        })
        .fail(function(xhr, status, error) {
            console.log('更新余额失败:', error);
            if (xhr.status === 403) {
                console.log('权限不足，停止自动更新余额');
                clearInterval(balanceUpdateInterval);
            }
        });
}

// 每30秒更新一次余额
var balanceUpdateInterval = setInterval(updateBalanceDisplay, 30000);
</script>
{% endblock %}